
package com.example.cia.database.mysql.dao.impl;

import java.sql.DriverManager;
import java.sql.SQLException;

import com.example.cia.database.mysql.IDatabaseConnection;
import com.mysql.jdbc.Connection;

public class databaseManager implements IDatabaseConnection{

	// 数据库连接常量
    public static final String DRIVER = "com.mysql.jdbc.Driver";
    public static final String USER = "root";
    public static final String PASS = "root";
    public static final String URL = "jdbc:mysql://localhost:3306/cia?useUnicode=true&characterEncoding=utf8";

    // 静态成员，支持单态模式
    private static databaseManager dbManager = null;
    private Connection con = null;
    
    private databaseManager(){
    	
    }
    
    public static databaseManager createInstance(){
    	if(dbManager==null){
    		dbManager = new databaseManager();
    		dbManager.initDb();
    	}
    	return dbManager;
    }
    
    public void initDb(){
    	try {
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
    }
    
    /*
     * 关闭获取的con后，需调用databaseManager的closeCon()关闭实例中的con。
     */
    public Connection getCon() throws SQLException{
    	con = (Connection) DriverManager.getConnection(URL, USER, PASS);
    	if(con!=null){
    		System.out.println("SqlManager:Connection to database successed.");
    	}else{
    		System.out.println("SqlManager:Connection to database failed.");
    	}
    	return con;
    }
    
    public boolean closeCon(){
    	try {
			con.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
    	return true;
    }
}
